<script>
import ZPMixin from '@/uni_modules/z-paging/components/z-paging/js/z-paging-mixin';
import { listOfPointsAudits } from '@/api/api.js';

export default {
  name: "index",
  mixins: [ZPMixin],
  data() {
    return {
      // 当前选择的Tab
      currentTab: 0,
      tabs: ['全部', '审核中', '已通过', '未通过'],
      // 票据列表数据
      ticketList: [],
      loading: false,
      // 无数据图标
      emptyIcon: '/static/images/empty-box.png',
      // 调试信息
      debug: {
        params: null,
        response: null,
        error: null
      }
    }
  },
  onLoad() {
    uni.setNavigationBarTitle({
      title: this.$t('receiptPoints.title')
    });
  },
  watch: {
    // 监听语言变化，更新导航栏标题
    '$i18n.locale'() {
      uni.setNavigationBarTitle({
        title: this.$t('receiptPoints.title')
      })
    }
  },
  methods: {
    // 切换Tab
    switchTab(index) {
      if (this.currentTab !== index) {
        this.currentTab = index;
        this.$refs.paging.reload();
      }
    },

    // 获取票据列表
    async queryList(pageNo, pageSize) {
      try {
        this.loading = true;

        // 构造状态参数
        let statusValue = '';
        switch (this.currentTab) {
          case 0: // 全部
            statusValue = '0,1,2,3';
            break;
          case 1: // 审核中
            statusValue = '0';
            break;
          case 2: // 已通过
            statusValue = '1,2';
            break;
          case 3: // 未通过
            statusValue = '3';
            break;
        }

        // 构造请求参数
        const params = {
          PageIndex: pageNo,
          PageSize: pageSize,
          WhereList: [{
            Name: 'Status',
            Type: 'In',
            Value: statusValue
          }]
        };

        // 保存请求参数用于调试
        this.debug.params = JSON.stringify(params);

        // 调用小票列表接口
        const res = await listOfPointsAudits(params);

        // 保存响应数据用于调试
        this.debug.response = JSON.stringify(res);

        this.loading = false;

        console.log("接口返回数据:", res);

        if (res.Data) {
          // 将接口返回的数据适配为组件需要的格式
          const formattedData = Array.isArray(res.Data) ? res.Data.map(item => {
            return {
              id: item.ID,
              title: this.$t('receiptPoints.labels.receiptPoints'),
              desc: `${this.$t('receiptPoints.labels.auditStatus', {status: this.getStatusText(item.Status)})}，${this.$t('receiptPoints.labels.uploadTime', {time: this.formatDate(item.AddTime)})}`,
              status: item.Status,
              btnText: this.getBtnText(item.Status),
              icon: '/static/my/sign-beans.png',
              imageUrl: item.InvoiceImg || '',
              addTime: item.AddTime,
              points: item.Points || 0,
              remark: item.Remark
            };
          }) : [];

          console.log("格式化后的数据:", formattedData);

          if (formattedData.length === 0) {
            console.log("列表数据为空");
          }

          this.$refs.paging.complete(formattedData);
        } else {
          console.log("返回数据异常:", res);
          this.$refs.paging.complete([]);
          console.error('获取票据列表失败:', res ? res.Message : '未知错误');
        }
      } catch (error) {
        console.error('获取票据列表失败:', error);
        this.debug.error = error.message || '未知错误';
        this.loading = false;
        this.$refs.paging.complete(false);
        uni.showToast({
          title: this.$t('merchants.loadFailed'),
          icon: 'none'
        });
      }
    },

    // 格式化状态文本
    getStatusText(status) {
      switch (parseInt(status)) {
        case 0:
          return this.$t('receiptPoints.status.pending');
        case 1:
        case 2:
          return this.$t('receiptPoints.status.approved');
        case 3:
          return this.$t('receiptPoints.status.rejected');
        default:
          return this.$t('receiptPoints.status.unknown');
      }
    },

    // 获取状态样式类
    getStatusClass(status) {
      switch (parseInt(status)) {
        case 0:
          return 'status-pending';
        case 1:
        case 2:
          return 'status-approved';
        case 3:
          return 'status-rejected';
        default:
          return '';
      }
    },

    // 获取按钮文本
    getBtnText(status) {
      switch (parseInt(status)) {
        case 0:
          return this.$t('receiptPoints.status.pending');
        case 1:
        case 2:
          return this.$t('receiptPoints.status.approved');
        case 3:
          return this.$t('receiptPoints.labels.reupload');
        default:
          return '查看';
      }
    },

    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '';

      // 处理字符串格式的日期 "2025-04-18 17:47:13"
      const parts = dateString.split(' ');
      if (parts.length >= 1) {
        return parts[0]; // 只返回日期部分
      }

      return dateString;
    },

    // 打开积分规则页面
    openRules() {
      uni.navigateTo({
        url: '/pages/article/index?id=4804&readOnly=true'
      });
    },

    // 根据类型处理按钮点击
    handleButtonClick(item) {
      if (parseInt(item.status) === 3) { // 未通过状态，可以重新上传
        this.goToUpload();
      } else if (item.imageUrl) { // 有图片链接，可以查看小票
        this.previewTicket(item.imageUrl);
      }
    },

    // 预览小票图片
    previewTicket(url) {
      if (!url) return;

      uni.previewImage({
        urls: [url],
        current: url
      });
    },

    // 去上传小票
    goToUpload() {
      uni.navigateTo({
        url: "/user_subpages/integral/upload"
      })
    }
  }
}
</script>

<template>
    <!-- 票据列表 -->
    <z-paging
      ref="paging"
      v-model="ticketList"
      @query="queryList"
      :refresher-enabled="true"
      :show-refresher-when-reload="true"
      loading-more-no-more-text="没有更多数据了"
      :empty-view-text="'暂无数据'"
      :empty-view-img="emptyIcon"
      :auto-show-back-to-top="true"
      :paging-style="{minHeight: '100vh', backgroundColor: '#F5F6F7'}"
    >
      <template #top>
        <!-- 规则入口 -->
        <view class="rules-header" @click="openRules">
          <image class="rules-icon" src="/static/icons/light-bulb.png" mode="aspectFit"></image>
          <text class="rules-text">{{$t('receiptPoints.rules.title')}}</text>
          <image class="rules-arrow" src="/static/icons/right-arrow.png" mode="aspectFit"></image>
        </view>

        <!-- 拍照上传卡片 -->
        <view class="upload-card">
          <view class="upload-content">
            <image class="upload-icon" src="https://wzws.wanshanlundiao.cn/upload/img/20250421/202504211811586136.png" mode="aspectFit"></image>
            <view class="upload-info">
              <view class="upload-header">
                <text class="upload-title">{{$t('receiptPoints.upload.photoTitle')}}</text>
                <view class="ai-tag">{{$t('receiptPoints.upload.aiTag')}}</view>
              </view>
              <text class="upload-desc">{{$t('receiptPoints.upload.photoDesc')}}</text>
            </view>
            <view class="upload-button" @click="goToUpload">
              <text>{{$t('receiptPoints.upload.goUpload')}}</text>
              <text class="btn-arrow">></text>
            </view>
          </view>
        </view>

        <!-- 选项卡 - 更新为order页面风格 -->
        <view class="navbar">
          <view
              v-for="(tab, index) in tabs"
              :key="index"
              :class="['nav-item', { current: currentTab === index }]"
              @click="switchTab(index)"
          >
            <text>{{$t(`receiptPoints.tabs.${index}`)}}</text>
          </view>
        </view>

        <!-- 调试信息 -->
        <view class="debug-info" v-if="debug.error">
          <view class="debug-title">错误信息：</view>
          <view class="debug-content">{{ debug.error }}</view>
        </view>
      </template>
      <view class="ticket-list">
        <!-- 调试信息 -->
        <view v-if="ticketList.length === 0 && !loading" class="empty-message">
          <text>未找到小票记录，请尝试上传小票或刷新页面</text>
        </view>

        <view
          class="ticket-item"
          v-for="(item, index) in ticketList"
          :key="index"
          @click="previewTicket(item.imageUrl)"
        >
          <!-- 小票信息 -->
          <view class="ticket-header">
            <view class="ticket-title-row">
              <text class="ticket-title">{{$t('receiptPoints.labels.receiptPoints')}}</text>
              <view class="ticket-status" :class="[getStatusClass(item.status)]">
                {{ getStatusText(item.status) }}
              </view>
            </view>
            <view class="ticket-time">{{$t('receiptPoints.labels.uploadTime', {time: formatDate(item.addTime)})}}</view>
          </view>

          <!-- 小票内容 -->
          <view class="ticket-content">
            <view class="ticket-image" v-if="item.imageUrl">
              <image :src="item.imageUrl" mode="aspectFill"></image>
            </view>
            <view class="ticket-details">
              <view class="ticket-detail-row">
                <text class="detail-label">{{$t('receiptPoints.labels.auditStatus', {status: getStatusText(item.status)})}}</text>
              </view>
              <view class="ticket-detail-row">
                <text class="detail-label">{{$t('receiptPoints.labels.earnedPoints', {points: item.points})}}</text>
              </view>
              <view class="ticket-detail-row" v-if="item.remark">
                <text class="detail-label">{{$t('receiptPoints.labels.remark', {remark: item.remark})}}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </z-paging>
</template>

<style scoped lang="scss">
/* 规则头部 */
.rules-header {
  background-color: #fdf6ec;
  padding: 24rpx 30rpx;
  display: flex;
  align-items: center;

  .rules-icon {
    width: 40rpx;
    height: 40rpx;
    margin-right: 10rpx;
  }

  .rules-text {
    flex: 1;
    font-size: 28rpx;
    color: #f9ae3d;
  }

  .rules-arrow {
    width: 24rpx;
    height: 24rpx;
  }
}

/* 使用order页面的navbar样式 */
.navbar {
  display: flex;
  height: 98rpx;
  background: #FFFFFF;
  position: relative;
  z-index: 10;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

  .nav-item {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    font-size: 24rpx;
    color: #666;
    position: relative;
    transition: all 0.3s ease;
    cursor: pointer;

    text{
      display: inline-block;
      padding: 10rpx 30rpx;
      border-radius: 30rpx;
      transition: all 0.4s cubic-bezier(0.25, 0.8, 0.25, 1);
      position: relative;
      z-index: 1;

      &:after {
        content: '';
        position: absolute;
        bottom: 6rpx;
        left: 50%;
        width: 0;
        height: 3rpx;
        background-color: #00BFFF;
        transition: width 0.3s ease, left 0.3s ease;
        z-index: 0;
      }
    }

    &:active text {
      transform: scale(0.95);
    }

    &.current {
      text{
        font-size: 30rpx;
        font-weight: 600;
        background-color: #00BFFF;
        color: #FFFFFF;
        transform: translateY(0) scale(1);
        animation: popIn 0.4s ease;

        @keyframes popIn {
          0% {
            transform: translateY(10rpx) scale(0.9);
            opacity: 0.7;
          }
          70% {
            transform: translateY(-5rpx) scale(1.05);
          }
          100% {
            transform: translateY(0) scale(1);
          }
        }
      }

      &:after {
        content: none;
      }
    }
  }
}

/* 拍照上传卡片 */
.upload-card {
  margin: 20rpx 30rpx;
  padding: 30rpx;
  background-color: #FFFFFF;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

  .upload-content {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;

    .upload-icon {
      width: 100rpx;
      height: 100rpx;
      border-radius: 50%;
      margin-right: 20rpx;
      background-color: #f5f5f5;
    }

    .upload-info {
      flex: 1;

      .upload-header {
        display: flex;
        align-items: center;
        margin-bottom: 10rpx;

        .upload-title {
          font-size: 32rpx;
          font-weight: 600;
          color: #333;
          margin-right: 10rpx;
        }

        .ai-tag {
          background-color: #72DFA8;
          color: #FFFFFF;
          font-size: 20rpx;
          padding: 2rpx 8rpx;
          border-radius: 6rpx;
        }
      }

      .upload-desc {
        font-size: 26rpx;
        color: #999;
        line-height: 1.4;
      }
    }
  }

  .upload-button {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding: 10rpx 24rpx;
    background-color: #00BFFF;
    border-radius: 30rpx;
    width: fit-content;
    margin-left: 20rpx;
    height: 58rpx;
    color: #fff;
    font-size: 26rpx;

    .btn-arrow {
      margin-left: 10rpx;
    }
  }
}

/* 票据列表 */
.ticket-list {
  padding: 30rpx 30rpx 20rpx;

  .empty-message {
    background-color: #FFFFFF;
    border-radius: 12rpx;
    padding: 40rpx 20rpx;
    text-align: center;
    margin-top: 20rpx;
    color: #999;
    font-size: 28rpx;
  }
}

.ticket-item {
  background-color: #FFFFFF;
  border-radius: 12rpx;
  padding: 24rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
  transition: transform 0.3s ease, box-shadow 0.3s ease;

  &:active {
    transform: translateY(2rpx);
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  }

  .ticket-header {
    padding-bottom: 20rpx;
    border-bottom: 1px solid #f5f5f5;

    .ticket-title-row {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 8rpx;

      .ticket-title {
        font-size: 32rpx;
        font-weight: 600;
        color: #333;
      }

      .ticket-status {
        font-size: 24rpx;
        padding: 4rpx 12rpx;
        border-radius: 20rpx;

        &.status-pending {
          background-color: #FFF8E6;
          color: #FAAD14;
        }

        &.status-approved {
          background-color: #E6F7FF;
          color: #1890FF;
        }

        &.status-rejected {
          background-color: #FFF1F0;
          color: #F5222D;
        }
      }
    }

    .ticket-time {
      font-size: 24rpx;
      color: #999;
    }
  }

  .ticket-content {
    display: flex;
    padding: 20rpx 0;

    .ticket-image {
      width: 160rpx;
      height: 160rpx;
      border-radius: 8rpx;
      overflow: hidden;
      margin-right: 20rpx;
      background-color: #f5f5f5;

      image {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }

    .ticket-details {
      flex: 1;

      .ticket-detail-row {
        display: flex;
        font-size: 26rpx;
        margin-bottom: 12rpx;

        .detail-label {
          color: #999;
          width: 150rpx;
        }

        .detail-value {
          color: #666;
          flex: 1;

          &.points {
            color: #F56C6C;
            font-weight: 600;
          }
        }
      }
    }
  }

  .ticket-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-top: 16rpx;
    border-top: 1px solid #f5f5f5;

    .ticket-hint {
      font-size: 24rpx;
      color: #F56C6C;
    }

    .action-btn {
      background-color: #FFFFFF;
      color: #00BFFF;
      font-size: 26rpx;
      padding: 8rpx 24rpx;
      border-radius: 30rpx;
      border: 1px solid #00BFFF;
      margin: 0;

      &.btn-reupload {
        background-color: #00BFFF;
        color: #FFFFFF;
      }

      .btn-arrow {
        margin-left: 4rpx;
      }
    }
  }
}

/* 调试信息 */
.debug-info {
  margin: 10rpx 30rpx;
  padding: 15rpx;
  background-color: #fff3cd;
  border-radius: 8rpx;
  font-size: 24rpx;

  .debug-title {
    font-weight: bold;
    margin-bottom: 10rpx;
  }

  .debug-content {
    word-break: break-all;
    color: #856404;
  }
}
</style>
